//
//  AddGpsDeviceViewController.swift
//  DSHCMerchant
//
//  Created by 罗德良 on 2018/5/4.
//  Copyright © 2018年 袋鼠好车. All rights reserved.
//

import UIKit
import CoreLocation
import Alamofire
class AddGpsDeviceViewController: BaseViewController {
    
    @IBOutlet var GPSNameTF: UITextField!
    
    @IBOutlet var distanceLabel: UILabel!
    
    @IBOutlet var GPSArddessLabel: UILabel!
    
    var gpsmodel:GPSModel?
    
    
    
    
    
    //定位管理器
    let locationManager:CLLocationManager = CLLocationManager()
    var lat = ""
    var lon = ""
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        locationManager.stopUpdatingLocation()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        baseSetNavRightButtonWithTitle("确定")
        if gpsmodel != nil {
            GPSNameTF.text = gpsmodel?.name
            distanceLabel.text = gpsmodel?.distance
            GPSArddessLabel.text = gpsmodel?.detail
            lat = (gpsmodel?.latitude)!
            lon = (gpsmodel?.longitude)!
        }
        
    }
    
    override func baseNavRightButtonPressed(_ button: UIButton) {
        requestAddService(gpsName: GPSNameTF.text!, distance: distanceLabel.text!, lat: lat, lon: lon, details: GPSArddessLabel.text!)
    }
    
    @IBAction func distanceBtnPress(_ sender: UIButton) {
        BRStringPickerView.showStringPicker(withTitle: "打卡范围", dataSource: ["50","100","200","300","400","500","600","700","800","900","1000"], defaultSelValue: self.gpsmodel?.distance ?? 50, isAutoSelect: true) { (str,index) in
            self.distanceLabel.text = str as? String
        }
        
    }
    
    
    @IBAction func getLocationBtnPress(_ sender: UIButton) {
        creatLocationManager()
    }
    
    
    func creatLocationManager() -> Void {
        //设置定位服务管理器代理
        locationManager.delegate = self as CLLocationManagerDelegate
        //设置定位进度
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        //更新距离
        locationManager.distanceFilter = 100
        ////发送授权申请
        locationManager.requestAlwaysAuthorization()
        if (CLLocationManager.locationServicesEnabled())
        {
            //允许使用定位服务的话，开启定位服务更新
            locationManager.startUpdatingLocation()
            print("定位开始")
        }
    }

    //添加Gps设备
    func requestAddService(gpsName:String,distance:String,lat:String,lon:String,details:String) -> Void {
        
        let param =
            ["name":gpsName,
             "distance":distance,
         "sid":UserModel.shareUser.data?.storeId ?? String(),
             "latitude":lat,
             "longitude":lon,
             "detail":details,
             ] as [String : Any]
        Alamofire.request(addGpsDeviceInfoUrl, method:.post, parameters:param)
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = DefaultData()
                    basemodel = DefaultData.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
                        hud?.mode = MBProgressHUDMode.text
                        hud?.labelText = "编辑成功"
                        hud?.show(animated: true, whileExecuting: {                        Thread.sleep(forTimeInterval: 0.8)
                        }, completionBlock: {                    self.navigationController?.popViewController(animated: true)
                        })

                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                    
                case false:
                    print(response.result.error!)
                }
                
        }
    }
    
    ///将经纬度转换为城市名
    func LonLatToCity(currLocation:CLLocation) {
        let geocoder: CLGeocoder = CLGeocoder()
        geocoder.reverseGeocodeLocation(currLocation) { (placemark, error) -> Void in
            
            if(error == nil)
            {
                let array = placemark! as NSArray
                let mark = array.firstObject as! CLPlacemark
                
                //城市
//                var city: String = (mark.addressDictionary! as NSDictionary).valueForKey("City") as! String
//                //国家
//                let country: NSString = (mark.addressDictionary! as NSDictionary).valueForKey("Country") as! NSString
//                //国家编码
//                let CountryCode: NSString = (mark.addressDictionary! as NSDictionary).valueForKey("CountryCode") as! NSString
//                //街道位置
                let FormattedAddressLines: NSString = ((mark.addressDictionary! as NSDictionary).value(forKey: "FormattedAddressLines") as AnyObject).firstObject as! NSString
                print(FormattedAddressLines)
//                //具体位置
                let Name: NSString = (mark.addressDictionary! as NSDictionary).value(forKey: "Name") as! NSString
                print(Name)
                
                self.GPSArddessLabel.text = FormattedAddressLines as String
                self.GPSNameTF.text = Name as String
                
                
//                //省
//                var State: String = (mark.addressDictionary! as NSDictionary).valueForKey("State") as! String
//                //区
//                let SubLocality: NSString = (mark.addressDictionary! as NSDictionary).valueForKey("SubLocality") as! NSString
//
//
//                //如果需要去掉“市”和“省”字眼
//
//                State = State.stringByReplacingOccurrencesOfString("省", withString: "")
//                let citynameStr = city.stringByReplacingOccurrencesOfString("市", withString: "")
                
                
                
                
            }
            else
            {
                print(error)
            }
        }
        
        
    }
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension AddGpsDeviceViewController: CLLocationManagerDelegate{
    
    //定位改变执行，可以得到新位置、旧位置
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        //获取最新的坐标
        let currLocation:CLLocation = locations.last!
        self.lat = "\(currLocation.coordinate.latitude)"
        self.lon = "\(currLocation.coordinate.longitude)"
        LonLatToCity(currLocation: currLocation)
        
        //        label1.text = "经度：\(currLocation.coordinate.longitude)"
        //        //获取纬度
        //        label2.text = "纬度：\(currLocation.coordinate.latitude)"
        //        //获取海拔
        //        label3.text = "海拔：\(currLocation.altitude)"
        //        //获取水平精度
        //        label4.text = "水平精度：\(currLocation.horizontalAccuracy)"
        //        //获取垂直精度
        //        label5.text = "垂直精度：\(currLocation.verticalAccuracy)"
        //        //获取方向
        //        label6.text = "方向：\(currLocation.course)"
        //        //获取速度
        //        label7.text = "速度：\(currLocation.speed)"
    }
    
}


